package de.koller.pulsar.scene.star;

import de.koller.aframe.util.misc.ColorOperations;
import de.koller.aframe.util.noise.n2D.Noise2D;
import de.koller.aframe.util.resource.IOLoader;
import de.koller.oceanFramework.gl.util.RasterManager;
import de.koller.oceanFramework.math.RVec2;
import de.koller.oceanFramework.util.ColorIntUtil;
import de.koller.pulsar.PNode;
import de.koller.pulsar.scene.IScene;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class StarScene  extends PNode implements IScene {
	public final Random RND = new Random();
	public final int WIDTH = 1000, HEIGHT = 1000;

	private RasterManager raster = new RasterManager( WIDTH, HEIGHT );		

	private final StarPhysics starPhysics = new StarPhysics();
	private List<FuzzyStar> stars = new ArrayList<>();
	
	@Override
	protected void init() {
		super.init();
		
		starPhysics.rotationCenter.set( WIDTH / 2, HEIGHT / 2 );
		starPhysics.velocity = 5;
		
		Noise2D n = new Noise2D( new float[][] {
			{ 0, -1, -1, 0 },
			{ -1, 0, 0, -1 },
			{ -1, 0, 0, -1 },
			{ 0, -1, -1, 0 }
		});
		
		//Function2DPreview.showFunction( 0, 0, 1, 1, n );
		for( int x = 0; x < WIDTH; x++ )
			for( int y = 0; y < HEIGHT; y++ ) {
				float r = n.getValue( 1f / WIDTH * x, 1f / HEIGHT * y );
				if( RND.nextFloat() > r ) continue;
				if( RND.nextInt( 1000 ) != 0 ) continue;
				
				FuzzyStar s = new FuzzyStar();
				s.position.set( x, y );
				s.radius = RND.nextFloat() * 300;
				s.color = ColorIntUtil.getIntColor( 0xff, 
						RND.nextInt( 0xff ),
						RND.nextInt( 0xff ),
						RND.nextInt( 0xff ) );
				stars.add( s );
			}
	}
	
	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
	
		raster.clear( 0xff000000 );
		
		int cs = 0;
		for( FuzzyStar s : stars ) {
			starPhysics.stepStar( s );
			
			for( Iterator<RVec2> i = s.getRenderIterator( 1 ); i.hasNext(); ) {
				RVec2 p = i.next();
				int c = s.render( p.x, p.y );
				setRaster( c, raster, (int)p.x, (int)p.y );
			}
			
			cs++;
			System.out.println( cs + " / " + stars.size() );
		}
		
//		int j = proot.setMovieFrame( IOLoader.create( raster ) );
//		if( j > 10000 )
			proot.setSceneFrame( IOLoader.create( raster ) );
	}
	
	private void setRaster( int c, RasterManager r, int x, int y ) {
		if( x < 0 || y < 0 || x >= r.getWidth() || y >= r.getHeight() )
			return;
		r.setPixel( ColorOperations.addComponent( r.colorAt( x, y ), c ), x, y );
	}
	
}
